#include "networkzingmeconnection.h"
#include "networkzingmewebsocket.h"
#include "./../networkconnectionrequest.h"

#include <QThread>
//#include <WebSocket>


using namespace Network::Zingme;

/**
 * @brief Connection::Connection
 * @param parent
 */
Connection::Connection(QObject *parent)
    : Network::Connection(parent)
    , m_disconnecting(false)
    , m_connecting(false)
    , m_worker(new QThread(this))
    , m_socket(new WebSocket)
{
    QObject::connect(this,
                     &Connection::connectReady,
                     m_socket,
                     &WebSocket::connect);

    QObject::connect(this,
                     &Connection::postReady,
                     m_socket,
                     &WebSocket::send);

    QObject::connect(this,
                     &Connection::disconnectReady,
                     m_socket,
                     &WebSocket::disconnect);

    QObject::connect(m_socket,
                     &WebSocket::connected,
                     this,
                     &Connection::onConnected);

    QObject::connect(m_socket,
                     &WebSocket::received,
                     this,
                     &Connection::onReceived);

    QObject::connect(m_socket,
                     &WebSocket::disconnected,
                     this,
                     &Connection::onDisconnected);


    m_socket->moveToThread(m_worker);
    m_worker->start();
}


Connection::~Connection()
{
    if (m_socket == NULL)
        return;

    delete m_socket;
    m_worker->quit();
    m_worker->wait();
    m_worker->deleteLater();
}


bool Connection::connect(const QString &url, unsigned int port, const QVariant &params)
{
    if (m_socket->isConnected())
        return false;

    if (m_connecting)
        return false;

    m_connecting = true;
    emit connectReady(url, port, params);
    return true;
}


bool Connection::isConnected() const
{
    return m_socket->isConnected();
}


bool Connection::post(Network::ConnectionRequest *request)
{
    if (!m_socket->isConnected())
        return false;

    emit postReady(request);
    return true;
}


bool Connection::disconnect()
{
    if (!m_socket->isConnected())
        return false;

    if (m_disconnecting)
        return false;

    m_disconnecting = true;
    emit disconnectReady();
    return true;
}


void Connection::onConnected()
{
    if (m_socket == NULL)
        return;

    if (!m_connecting)
        return;

    m_connecting = false;
    emit connected();
}


void Connection::onReceived(QByteArray message)
{
    emit received(message);
}


void Connection::onDisconnected()
{
    if (m_socket == NULL)
        return;

    qDebug()<<"Connection onDisconnected, emiting disconnected ";
    emit disconnected();
//    if (!m_disconnecting)
//        return;

//    delete m_socket;
//    m_socket = NULL;
}
